package graphics;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import java.io.File;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import dao.*;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

import ui.mainWindow;
import java.sql.SQLException;
import java.awt.event.*;

public class SizePieChart {
	public static void main(String[] args) throws SQLException {
		
	// Create a simple pie chart
		DefaultPieDataset pieDataset = new DefaultPieDataset();
		
		PreparedStatement comandoSelect = ConnectionManager.getConnection().prepareStatement("SELECT DISTINCT size FROM bird");
		ResultSet resultados = comandoSelect.executeQuery();
		PreparedStatement comandoSelect2 = ConnectionManager.getConnection().prepareStatement("SELECT size AS cont FROM bird");
		ResultSet totalRows = comandoSelect2.executeQuery();
		
		int countRows = 0;
		while(totalRows.next()){
			countRows++;
		}
		System.out.println("TotalRows:"+countRows);
		int totalFound = 0;
		while(resultados.next())
		{
			
			String size = resultados.getString(1);
			PreparedStatement comandoSelect3 = ConnectionManager.getConnection().prepareStatement("SELECT size AS cont2  FROM bird WHERE size = "+size+" ");
			ResultSet totalRegsFound = comandoSelect3.executeQuery();
			while(totalRegsFound.next()){
				totalFound++;
			}
			
			
			pieDataset.setValue(size + "cm", (totalFound*100/countRows));
			totalFound=0;
			/*Sample Code:
			pieDataset.setValue("Ubuntu", new Integer(75));
			pieDataset.setValue("Xubuntu", new Integer(10));
			pieDataset.setValue("Kubuntu", new Integer(10));
			pieDataset.setValue("Otros", new Integer(5));
			*/
		}
		
		JFreeChart chart = ChartFactory.createPieChart(
		"Birds by size %",
		pieDataset,
		true,
		true,
		false);
		try {
			ChartUtilities.saveChartAsJPEG(new File("size.jpg"), chart, 500,
			500);
		} catch (Exception e) {
			System.out.println("Erro criando grafico.");
			
		}
		
		final JFrame viewFrame = new JFrame("Size PieChart");
		ImageIcon img = new ImageIcon("size.jpg");
		JLabel etiqueta = new JLabel(img);
		viewFrame.getContentPane().add(etiqueta);
        viewFrame.setSize(800, 800);
        viewFrame.setVisible(true);        
		
		viewFrame.addWindowListener(new WindowAdapter()
		{
			public void windowClosing(WindowEvent evt)
			{
				viewFrame.dispose();
			}
		});
	}
}